const app = getApp();
import { orderList, getOrderReturnAddress, orderReturnAddExpress, orderApplyReturn, getReturnExpressList,
   orderReturnCancel, orderPreAuth, getRenewalGoodsStatus,createWithholdSign,getNotaryUrl} from "../../../api/order";
import { getBtnsByStatus, cancelOrder, cancelRefundApply, payFirstRent, confirmReceipt } from "../../../utils/order";
import { programTitle } from "../../../setting";
import {createContract,createAntchain,orderInsuranceBuy} from "../../../api/index";
Page({
  data: {
    defaultName: programTitle,
    tabs: [
      { id: 0, title: '全部' },
      { id: 2, title: '待付款' },
      { id: 10, title: '待发货' },
      { id: 20, title: '待收货' },
      { id: 30, title: '租赁中' },
      { id: 40, title: '归还订单' },
      { id: 50, title: '续租订单' },
      { id: 62, title: '买断订单' },
      { id: 60, title: '已完成' },
      { id: 1, title: '订单关闭' }
    ],
    activeTab: 0,
    orderList: [],
    page: 1,
    pageSize: 10,
    total: 0,
    loadTip: '',
    showLoading: false,
    showTopBtn: false,
    isloading: true,
    showService: false,
    currentMId: '',
    returnAddress: {},
    addressModal: false,
    addressBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '复制地址', extClass: 'button2' },
    ],
    addressOneBtn: [
      { text: '返回', extClass: 'button1' },
    ],
    returnModal: false,
    returnBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '确认归还', extClass: 'button2' },
    ],
    returnApplyBtn: [
      { text: '取消申请', extClass: 'button1' },
      { text: '确认申请', extClass: 'button2' },
    ],
    order_id: '',
    insurance:'',
    status: 0,
    flowModal: false,
    flowList: [],
    flowIndex: -1,
    flowNo: '',
    placeholder: '请填写物流单号',
    disabledInput: false,
    reletModal: false,
    goodsStatus: '',
    goodsId: '',
    setmealId: ''
  },
  onLoad(options) {
    if(options.order_status>-1){
      const index = this.data.tabs.findIndex(item => item.id == options.order_status);
      this.setData({
        activeTab: index || 0
      })
    }
    this.getList();
  },
  onShow(){
    // this.getList();
    this.setData({
      reletModal: false,
    })
  },
  getList(flag) {
    // flag为true时加载更多
    const { tabs, activeTab, page, pageSize } = this.data;
    const order_status = activeTab>=0?tabs[activeTab].id:0;
    const params = order_status ? {
      order_status, page: flag ? page + 1 : 1,
      pageSize
    } : {
        page: flag ? page + 1 : 1,
        pageSize
      };
    this.setData({
      isloading: true
    })
    orderList(params).then(res => {
      my.stopPullDownRefresh();
      for (let item of res.data) {
        item.btns = getBtnsByStatus(item);
        item.showMore = false;
      }
      let list = [...this.data.orderList];
      if (flag) {
        list = [...list, ...res.data];
      } else {
        list = res.data;
      }
      this.setData({
        orderList: list,
        page: res.current_page,
        total: res.total,
        isloading: false,
        showLoading: false,
        order_id:res.id,
        // insurance:res.is_insurance_choose
      })
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  goToShop(e) {
    const member_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../../../pages/storeDetails/storeDetails?member_id=' + member_id
    });
  },
  goToHome() {
    my.switchTab({
      url: '../../../pages/index/index'
    });
  },
  goToDetail(e) {
    const order_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../../../pages/user/orderpay/orderpay?id=' + order_id
    });
  },
  handleTabClick({ index, tabsName }) {
    this.setData({
      [tabsName]: index
    });
    my.pageScrollTo({
      scrollTop: 0
    });
    this.getList();
  },
 
  setReason(e){
     const that = this;
     cancelOrder({order_id:this.data.order_id,name:e}, function () {
         that.getList();
         that.setData({
          showReasonPicker: false
        })
      })
  },
  closeReasonPicker() {
    this.setData({
      showReasonPicker: false
    })
  },
  btnClick(e) {
    const that = this;
    const { index, id, status, order_id, face_flow_id,isAuth, pay_type, esignUserId, flowId, sign_status, member_id, goods_id, contract_type, insurance_id} = e.currentTarget.dataset;
    this.setData({
      order_id,
      status
    })
    if (index || index === 0) {
      const { orderList } = this.data;
      orderList[index].showMore = false;
      this.setData({ orderList });
    }
    if (id == 2) {
      this.setData({
        showReasonPicker: true,
      })
      const list = [
        {value: 7,name: '价格有点贵',checked: false},
        {value: 1,name: '商品拍错(机型/规格/颜色/套餐)',checked: false},
        {value: 2,name: '收货号码/地址填写错误',checked: false},
        {value: 3,name: '发货太慢了',checked: false},
        {value: 4,name: '没用/少用优惠',checked: false},
        {value: 5,name: '计划有变暂时不需要了',checked: false},
        {value: 6,name: '其他',checked: false},
    ];
     

      this.setData({reasonList:list});
     
    }
    if (id == 9) {
      my.navigateTo({
        url: '../applyRefund/applyRefund?order_id=' + order_id
      });
    }
    if (id == 18) {
      cancelRefundApply(order_id, function () {
        that.getList();
      })
    }
    if (id == 3 && status == 20) {
      confirmReceipt(order_id, function () {
        that.getList();
      })
    }
    if ((id == 6 && status == 44) || id == 19) {
      my.navigateTo({
        url: '../logistics/logistics?order_id=' + order_id + '&status=' + status
      });
    }
    if (id == 4) {
      // return
      my.navigateTo({
        url: '../bill/bill?order_id=' + order_id
      });
    }
    if(id=='99'){
      my.navigateTo({
        url: '../../../pages/authentication/authentication?orderId=' + order_id+'&contractType=2&&payType=1'
      })
    }
   
    // if ((id == 1 || id == 20) && (status == 2 || sign_status != 2)) {
    //   my.navigateTo({
    //     url: '../authentication/authentication?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&status=' + status + '&contractType=' + contract_type
    //   });
    // }
    // if (id == 1 || id == 20 && (status == 9 || 10)) {
    if (id == 20) { //230303修改
      my.navigateTo({
        url: '../../../pages/authentications/authentications?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&face_flow_id='+face_flow_id+'&status=' + status + '&contractType=' + contract_type+ '&type=2'
      });
      //签署合同
      /*
      my.showLoading({
        content:'合同生成中...',
        success:(res=>{
          this.createContractMe(order_id,pay_type);
        })
      })
      setTimeout(() => {
        my.hideLoading()
      }, 3000);
      */
    }
    if(id==30){

      createWithholdSign(order_id).then(res => {
          my.navigateToMiniProgram({
            appId:"2021001152620480", // 区块链合同真实appId
            path:"pages/tripartite/index", // 支付宝商家跳转区块链合同代扣签署地址（真实路径
            query:{
            signStr:res.signStr,// 签署代扣必要的字符串参数
            tenantId:"GLRPPYWX",
            merchantId:"91310117MAE30K4D1P",
            orderId:res.orderId,
            redirectUrl:"alipays://platformapi/startapp?appId=2021005103687601&page=pagesA/pages/myOrder/myOrder", // 代扣签署成功/失败回跳地址，示例 alipays://platformapi/startapp?appId=2021004108689505&page=pages/home/index，appId 和 page 需要根据实际情况调整真实数值
            }, // 需要携带的必要参数
            success: () => {},
            fail: () => {},
            });
     
        });
      }
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
      // payFirstRent(order_id, function () {
      //   that.getList();
      // })
      my.navigateTo({
        url: '../paymentPage/paymentPage?order_id=' + order_id
      })
    }
    if (id == 17) {
      this.setData({
        currentMId: member_id,
        showService: true
      })
    }
    if (id == 7) {
      my.navigateTo({
        url: '../productDetails/productDetails?goodsId=' + goods_id+'&sale_user_id='+app.globalData.sale_user_id
      });
    }
    if (id == 14) {
      my.navigateTo({
        url: '../buyout/buyout?orderId=' + order_id
      });
    }
    // 立即归还
    if (id == 11) {
      if(status == 40){
        this.setData({
          returnModal: true
        })
      } else if(status == 42){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      }
    }
    // 获取归还地址
    if (id == 16) {
      getOrderReturnAddress(order_id).then(res => {
        if(res){
          this.setData({
            returnAddress: res,
            addressModal: true
          })
        }
      }).catch(err => {
        this.setData({
          addressModal: false
        })
      })
    }
        // 协议公证
        if(id == 31){
          getNotaryUrl(order_id).then(res =>{
            let data=res.data.weiXinHttpUrl;
              my.setClipboard({
                text: data,
                success: () => {
                  my.alert({
                    content: '复制链接成功，请用浏览器打开链接前往视频公证',
                    buttonText: '我知道了'
                  })
                }
              });
          })
        }
    // 取消归还
    if(id == 5){
      orderReturnCancel(order_id).then(res =>{
        my.showToast({
          type: 'none',
          content: '操作成功',
          duration: 1000,
        });
        that.getList();
      })
    }
    // 申请归还
    if(id == 10){
      this.setData({
        returnModal: true
      })
    }
    // 再次申请
    if(id == 12){
      orderApplyReturn(order_id).then(res =>{
        that.getList();
      })
    }
    // 重新签约
    if(id == 22){
      that.againPreAuth()
    }
    // 申请续租
    if(id == 15){
      getRenewalGoodsStatus(order_id).then(res =>{
        const {goods_id, setmeal_id, status } = res
        if(status == 1){
          this.setData({
            reletModal: true,
            goodsStatus: status,
            goodsId: goods_id,
            setmealId: setmeal_id
          })
        } else {
          this.setData({
            reletModal: true,
            goodsStatus: '',
          })
        }
      }).catch(err =>{
        this.setData({
          reletModal: false,
          goodsStatus: '',
        })
      })
    }

  },
  createContractMe(orderId,pay_type){
    const env = 'prod'
    if(pay_type == 2){
    // const that = this
    // createContract(orderId).then(res => {
    //   if (res.flowId) {
    //     my.hideLoading({ page: this });
    //     my.setStorage({ key: 'hasCreateSign', data: true });
    //     const { flowId, signerId } = res
    //     my.navigateTo({
    //       url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
    //     })
    //   }
    // })
    const that = this
    createAntchain(orderId).then(res => {
      console.log('res', res)
      my.showLoading({ content: '正在跳转合同...' });
      function getSignUrl(aliSchema) {
        if (!aliSchema) { return '' }
        const querys = aliSchema.split('?')[1].split('&');
        const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
        const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
        return encodedSignUrl
      }
      const signUrl = getSignUrl(res.sign_url);
      my.navigateToMiniProgram({
        appId: '2021001152620480',
        path: `pages/signH5/index?signUrl=${signUrl}`,
        success: (res) => {
          console.log(JSON.stringify(res))
          my.hideLoading({
            page: that,
          });
        },
        fail: (res) => {
          my.hideLoading({
            page: that,
          });
          console.log(JSON.stringify(res))
        }
      });
    })
      }else if(pay_type == 1){
        my.navigateTo({
          url: '../chainContract/chainContract?orderId=' + orderId
        })
      }
  },
  onReletClick(){
    const {goodsId, setmealId, goodsStatus, order_id } = this.data
    if(!goodsStatus){
      this.setData({
        reletModal: false,
        goodsStatus: ''
      })
    } else {
      my.navigateTo({
        url: "../productDetails/productDetails?goodsId=" +goodsId+ '&setmealId=' +setmealId+ '&is_renewal=' +1+ '&parent_order_id=' + order_id+'&sale_user_id='+app.globalData.sale_user_id
      })
    }
  },
  // 签约预授权
  againPreAuth(){
    const that = this
    orderPreAuth(that.data.order_id).then(res =>{
        if(res.orderStr){
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              that.getList();
              // if(res.resultCode == 9000){}
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '签约失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        }
    })
  },
  onAddressClick(e) {
    let index = e.target.dataset.index
    if (index == 0) {
      this.setData({
        addressModal: false,
      });
    } else {
      my.setClipboard({
        text: this.data.returnAddress,
        success: () => {
          my.showToast({
            type: 'none',
            content: '复制成功',
            duration: 1000,
          });
        }
      });
    }
  },
  onReturnClick(e) {
    const that = this
    let index = e.target.dataset.index
    if (index == 0) {
      that.setData({
        returnModal: false,
      });
    } else {
      const {order_id, status} = that.data
      if(status == 40){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      } else if( status==30|| status==39 ){
        orderApplyReturn(order_id).then(res =>{
          that.getList();
          that.setData({
            returnModal: false
          });
        })
      }
    }
  },
  bindPickerChange(e){
    this.setData({
      flowIndex: e.detail.value,
      disabledInput: e.detail.value == 0 ? true : false,
      placeholder: e.detail.value == 0 ? '无需填写单号' : '请填写物流单号',
    });
  },
  onFlowNo(e){
    let reg = /^[0-9A-Za-z]+$/
    if(!reg.test(e.detail.value)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
    }
    this.setData({ flowNo: e.detail.value })
  },
  toAddFlow(){
    const that = this
    const { order_id, flowIndex, flowNo, flowList} = that.data
    const reg = /^[0-9A-Za-z]+$/
    if(flowIndex < 0){
      my.showToast({
        type: 'none',
        content: '请选择物流名称',
        duration: 1500,
      });
      return false 
    }
    if(!flowNo && flowIndex >0){
      my.showToast({
        type: 'none',
        content: '请填写物流单号',
        duration: 1500,
      });
      return false 
    }
    if(flowNo && !reg.test(flowNo)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
      return false
    }
    orderReturnAddExpress({
      order_id,
      logistics_name: flowList[flowIndex].name,
      logistics_no: flowNo,
    }).then(res =>{
      this.setData({
        flowModal: false
      });
      that.getList();
    })
  },
  closeModal(){
    this.setData({
      flowModal: false
    })
  },
  closeService() {
    this.setData({
      showService: false
    })
  },
  clickMore(e) {
    const index = e.currentTarget.dataset.index;
    const list = [...this.data.orderList];
    list[index].showMore = !list[index].showMore;
    this.setData({
      orderList: list
    })
  },
  onReachBottom() {
    // 页面拉到底部
    const { orderList, total } = this.data;
    if (orderList.length < total) {
      this.setData({
        showLoading: true
      })
      this.getList(true);
    } else if (total > 4) {
      this.setData({
        loadTip: '没有更多数据了'
      })
    }
  },
  onPullDownRefresh() {
    this.getList();
  },
  onPageScroll(e) {
    this.setData({
      showTopBtn: e.scrollTop > 600
    })
  }
});
